package com.cby.android.olive.ext

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText

/**
 * @description: EditText的拓展
 * @author: ChenBaoYang
 * @createDate: 2022/7/14 5:41 下午
 */

/**
 * 高阶函数写法
 * @receiver EditText
 * @param afterTextChanged Function1<String, Unit>
 */
fun EditText.afterTextChange(afterTextChanged: (String) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {

        override fun afterTextChanged(s: Editable?) {
            afterTextChanged.invoke(s.toString())
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }
    })
}

/**
 * DSL写法
 * @receiver EditText
 * @param block [@kotlin.ExtensionFunctionType] Function1<MyTextWatcher, Unit>
 */
fun EditText.addAfterTextChange(block: MyTextWatcher.() -> Unit) {
    val callback = MyTextWatcher()
    callback.block()

    addTextChangedListener(callback)
}

private typealias BeforeTextChangedCallback =
            (s: CharSequence?, start: Int, count: Int, after: Int) -> Unit

private typealias OnTextChangedCallback =
            (s: CharSequence?, start: Int, before: Int, count: Int) -> Unit

private typealias AfterTextChangedCallback = (s: Editable?) -> Unit

class MyTextWatcher : TextWatcher {

    private var afterTextChangedEx: AfterTextChangedCallback? = null

    private var onTextChangedEx: OnTextChangedCallback? = null

    private var beforeTextChangedEx: BeforeTextChangedCallback? = null

    fun beforeTextChanged(method: BeforeTextChangedCallback?) {
        beforeTextChangedEx = method
    }

    fun onTextChanged(method: OnTextChangedCallback?) {
        onTextChangedEx = method
    }

    fun afterTextChanged(method: AfterTextChangedCallback?) {
        afterTextChangedEx = method
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        beforeTextChangedEx?.invoke(s, start, count, after)
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        onTextChangedEx?.invoke(s,start, before, count)
    }

    override fun afterTextChanged(s: Editable?) {
        afterTextChangedEx?.invoke(s)
    }

}